<template>
  <el-dialog :close-on-click-modal="false" :visible.sync="userAddFormVisible" center title="添加用户" top="25vh"
             width="30%">
    <el-form ref="form" :model="form" :rules="rules" size="medium">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="form.userName" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="form.role">
          <el-option v-for="item in selectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-button @click="resetForm" size="mini">重置</el-button>
        </el-col>
        <el-col :offset="6" :span="12">
          <el-button @click="userAddFormVisible = false" size="mini">取 消</el-button>
          <el-button type="primary" @click="commit" size="mini">确 定</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      form: {
        userName: "",
        password: "",
        role: 0,
      },
      rules: {
        userName: [
          {required: true, message: "请输入用户名", trigger: "blur"}
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"}
        ]
      },
      userAddFormVisible: false,
      selectList: [
        {
          value: 0,
          label: '普通用户'
        },
        {
          value: 1,
          label: '管理员'
        }
      ]
    }
  },
  methods: {
    showAddUserForm() {
      this.userAddFormVisible = true;
    },
    commit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$axios.post("/api/user/add", this.form).then(res => {
            if (res.code === 0) {
              this.$message.success("添加成功");
              this.$emit("success-add");
              this.userAddFormVisible = false;
            } else {
              if (res.discription !== "") {
                this.$message.error(res.message + "，" + res.description);
              } else {
                this.$message.error(res.message);
              }
            }
          }).catch(err => {
            this.$message.error("修改失败");
          });
        } else {
          this.$message.error("输入内容有误");
        }
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
  },
  mounted() {
    document.body.appendChild(this.$el);
  },
  beforeDestroy() {
  },
  destroyed() {
    if (this.$el && this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el);
    }
  }
}
</script>

<style lang="scss" scoped>

</style>